package cn.zcj.studytest.service;

import cn.zcj.studytest.ThrowData.Result;
import cn.zcj.studytest.domain.Message;
import cn.zcj.studytest.domain.SignUp;
import cn.zcj.studytest.mapper.MessageMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class MessageService extends ServiceImpl<MessageMapper, Message> {
    @Autowired
    private SignUpService signUpService;

    public Result getMessage(Message message){
        Result result = new Result();
        List<Message> list  = this.lambdaQuery().eq(Message::getName, message.getName()).orderByDesc(Message::getTime).list();
        result.setData(list);
        result.ok("获取成功！");
        result.setSuccess(true);
        return result;
    }

    public Result insertMessage(Message message){
        Result result = new Result();
        try {
            // 获取当前用户
            Long userId = message.getUserId();
            // 获取当前用户 得到他的余额
            SignUp signUpObj = signUpService.getById(userId);
            if (signUpObj.getPrice() < 1){
                result.setMsg("余额不足");
                result.setSuccess(false);
                return result;
            }
            // 余额减一
            double price = signUpObj.getPrice() - 1;
            signUpService.lambdaUpdate()
                    .eq(SignUp::getId, userId)
                    .set(SignUp::getPrice, price)
                    .update();
            // 插入数据
            LocalDateTime time = LocalDateTime.now();
            message.setTime(time);
            this.save(message);
            result.ok("插入成功！");
            result.setSuccess(true);
            return result;
        }catch (Exception e){
            result.setMsg("插入失败");
            result.setSuccess(false);
            return result;
        }
    }
}
